package io.wongxd.solution.util

import android.content.Intent
import androidx.activity.ComponentActivity
import androidx.activity.result.ActivityResult
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleOwner
import java.util.concurrent.atomic.AtomicInteger
import kotlin.properties.Delegates

private val nextLocalRequestCode = AtomicInteger()

private val nextKey: String
    get() = "activity_rq#${nextLocalRequestCode.getAndIncrement()}"

fun ComponentActivity.startForResult(
    input: Intent,
    output: (ActivityResult) -> Unit
) {
    var launcher by Delegates.notNull<ActivityResultLauncher<Intent>>()
    launcher = activityResultRegistry.register(
        nextKey,
        ActivityResultContracts.StartActivityForResult()
    ) { result ->
        output.invoke(result)
        launcher.unregister()
    }
    lifecycle.addObserver(object : LifecycleEventObserver {
        override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
            if (event == Lifecycle.Event.ON_DESTROY) {
                launcher.unregister()
                lifecycle.removeObserver(this)
            }
        }
    })
    launcher.launch(input)
}


//fun FragmentActivity.startActivityForResult(
//    intent: Intent,
//    requestCode: Int,
//    callback: (resultCode: Int, data: Intent?) -> Unit
//) = DispatchResultFragment.getInstance(this).startActivityForResult(intent, requestCode, callback)
//
//class DispatchResultFragment : Fragment() {
//    private val callbacks = SparseArray<(resultCode: Int, data: Intent?) -> Unit>()
//
//    override fun onCreate(savedInstanceState: Bundle?) {
//        super.onCreate(savedInstanceState)
//        retainInstance = true
//    }
//
//    fun startActivityForResult(
//        intent: Intent,
//        requestCode: Int,
//        callback: (resultCode: Int, data: Intent?) -> Unit
//    ) {
//        callbacks.put(requestCode, callback)
//        startActivityForResult(intent, requestCode)
//    }
//
//    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
//        super.onActivityResult(requestCode, resultCode, data)
//        val callback = callbacks.get(requestCode)
//        if (callback != null) {
//            callback.invoke(resultCode, data)
//            callbacks.remove(requestCode)
//        }
//    }
//
//    companion object {
//        private const val TAG = "dispatch_result"
//
//        fun getInstance(activity: FragmentActivity): DispatchResultFragment {
//            val fragmentManager = activity.supportFragmentManager
//            var fragment = fragmentManager.findFragmentByTag(TAG) as DispatchResultFragment?
//            if (fragment == null) {
//                fragment = DispatchResultFragment()
//                fragmentManager.beginTransaction().add(fragment, TAG).commitAllowingStateLoss()
//                fragmentManager.executePendingTransactions()
//            }
//            return fragment
//        }
//    }
//}
